package com.example.design.bridge.function;

import com.alibaba.fastjson.JSONObject;
import com.example.design.bridge.abst.factory.RegisterLoginComponentFactory;
import com.example.design.pojo.UserInfo;
import com.example.design.repo.UserRepository;
import com.example.design.utils.HttpClientUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
public class RegisterLoginByGitee extends AbstractRegisterLoginFunc implements RegisterLoginFuncInterface {

    @Value("${gitee.state}")
    private String giteeState;

    @Value("${gitee.token.url}")
    private String giteeTokenUrl;

    @Value("${gitee.user.url}")
    private String giteeUserUrl;

    @Value("${gitee.user.prefix}")
    private String giteeUserPrefix;


    @Resource
    private UserRepository userRepository;


    @PostConstruct
    private void initFuncMap() {
        RegisterLoginComponentFactory.funcMap.put("GITEE", this);
    }


    @Override
    public String login3rd(HttpServletRequest request) {
            String state = request.getParameter("state");
        String code = request.getParameter("code");
        //进行state判断，state值是前端和后端约好的，前端将state传给gitee,gitee平台传回state给回调接口
        if (!giteeState.equals(state)) {
            throw new UnsupportedOperationException("state值不匹配");
        }
        //获取token
        String tokenUrl = giteeTokenUrl.concat(code);
        JSONObject jsonObject = HttpClientUtils.execute(tokenUrl, HttpMethod.POST);
        String token = String.valueOf(jsonObject.get("access_token"));
        System.out.println(token);
        //请求用户信息并携带token
        String userUrl = giteeUserUrl.concat(token);
        JSONObject userInfoResponse = HttpClientUtils.execute(userUrl, HttpMethod.GET);
        //获取用户信息，userName添加前缀GITEE@，密码保持与UserName一致
        String userName = giteeUserPrefix.concat(String.valueOf(userInfoResponse.get("name")));
        return autoRegister3rdLogin(userName, userName);
    }

    public String autoRegister3rdLogin(String userName, String password) {
        //如果第三方账号已经注册过，直接登录
        if (super.commonCheckUserExists(userName,userRepository)) {
            return super.commonLogin(userName, password,userRepository);
        }
        //组装用户信息
        UserInfo userInfo = new UserInfo();
        userInfo.setUserName(userName);
        userInfo.setUserPassword(password);
        userInfo.setCreateDate(new Date());
        //如果第三方账号是第一次登录，先进行自动登录
        super.commonRegister(userInfo,userRepository);
        //自动注册成功后，登录
        return super.commonLogin(userName, password,userRepository);
    }
}
